from collections import defaultdict


async def load_cache_data():
    # 初始化租户的邀请码
    from common.g.g import G_REDIS
    from common.g.g import G_MGW
    from common.v.v import TENANT
    from common.model.tenant.tenant import Tenant
    from common.model.user.tenant_user import MiddleTenantUserForTenant

    async def load_invite_code():
        q = Tenant.select(Tenant.invite_code, Tenant.tenant_id).where(Tenant.removed == False)
        d = await G_MGW.execute(q)
        c_l = []
        t_l = []
        for i in d:
            c_l.append(i.invite_code)
            t_l.append(i.tenant_id)
        await G_REDIS.sadd(TENANT.TENANT_INVITE_CODE_SET, *c_l)
        return t_l

    async def load_tenant_user(tenant_id_list):
        query = MiddleTenantUserForTenant.select(MiddleTenantUserForTenant.user_id,
                                                 MiddleTenantUserForTenant.tenant_id).\
            where(MiddleTenantUserForTenant.removed == False,
                  MiddleTenantUserForTenant.tenant_id.in_(tenant_id_list))
        d = await G_MGW.execute(query)
        t_to_i_d = defaultdict(list)
        for i in d:
            t_to_i_d[i.tenant_id].append(i.user_id)
        for t_id, u_list in t_to_i_d.items():
            await G_REDIS.sadd(TENANT.TENANT_USER_SET.format(tenant_id=t_id), *u_list)

    t_list = await load_invite_code()
    await load_tenant_user(t_list)



